package javabasic.threads.CreateThreadMethods;

import java.util.concurrent.*;

/**
 * 向线程池提交的可以是线程实例  也可以是实现了runnable或callable接口的任务，提交任务后返回的是future对象
 * 线程池提交内容：
 * 1、可以提交子线程
 * 2、可以提交实现了runnable接口的实例，而非线程
 * 3、可以提交实现了callable接口的实例，而非线程
 * 4、提交线程池后，返回的是future对象
 */


public class Method06PoolCallable {
    public static void main(String[] args) {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        Future future = cachedThreadPool.submit(new CallablePool(0));
        while (!future.isDone()){
            System.out.println("子线程未执行完毕，请等待。。。。。。");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("子线程执行完毕");
        try {
            System.out.println(future.get());
            cachedThreadPool.shutdown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

class CallablePool implements Callable{
    private int sum;

    public CallablePool(int sum) {
        this.sum = sum;
    }

    @Override
    public Integer call() throws Exception {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"------"+i);
            Thread.sleep(100);
            this.sum+=i;
        }
        return this.sum;
    }
}